package com.yunduo.world.handler;

import com.yunduo.world.constant.NetWorkConstant;
import com.yunduo.world.utils.ClientUtils;
import com.yunduo.world.utils.EntityBuild;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.timeout.IdleStateEvent;
import lombok.extern.slf4j.Slf4j;

/**
 * 客户端心跳处理
 */
@Slf4j
public class ClientHeartHandler extends ChannelInboundHandlerAdapter {

    @Override
    public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
        if (evt instanceof IdleStateEvent) {
            IdleStateEvent heartEvent = (IdleStateEvent) evt;
            switch (((IdleStateEvent) evt).state()) {
                case ALL_IDLE,READER_IDLE -> {
                    ctx.writeAndFlush(EntityBuild.buildMessage(NetWorkConstant.NET_WORK,"长时间未操作,已登出。 用户" + ClientUtils.get(ctx.channel()) + "退出",NetWorkConstant.NOT_OK));
                    log.info("长时间未操作,已登出。 用户" + ClientUtils.get(ctx.channel()) + "退出");
                    ClientUtils.removeChannel(ctx.channel());
                }
                case WRITER_IDLE -> {
                    log.info(ClientUtils.get(ctx.channel()) + "长时间未操作,即将登出。");
                    ctx.writeAndFlush(EntityBuild.buildMessage(NetWorkConstant.NET_WORK,"长时间未操作,即将登出。", NetWorkConstant.OK));
                }
            }
        }
    }
}
